'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

interface Brand {
  brand: string;
  name: string;
  alphabet: string;
  country: string;
  hot: string;
  desc: string;
  story: string;
}

interface Car {
  id: string;
  name: string;
  brand: string;
  type: string;
  price: number;
  image: string;
}

export default function BrandsPage() {
  const { user } = useAuth();
  const router = useRouter();
  const [brands, setBrands] = useState<Brand[]>([]);
  const [cars, setCars] = useState<Car[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedAlphabet, setSelectedAlphabet] = useState<string>('全部');
  const [selectedCountry, setSelectedCountry] = useState<string>('全部');

  useEffect(() => {
    if (!user || user.role !== 'admin') {
      router.push('/login');
      return;
    }

    // 加载品牌数据
    const loadBrandData = async () => {
      try {
        const brandData = await import('@/../public/brandData.js');
        setBrands(brandData.default);
        
        // 模拟车辆数据
        const mockCars: Car[] = [
          { id: '1', name: 'Model S', brand: 'tesla', type: '纯电动', price: 799900, image: '/cars/tesla-model-s.jpg' },
          { id: '2', name: '汉EV', brand: 'byd', type: '纯电动', price: 219800, image: '/cars/byd-han.jpg' },
          { id: '3', name: '理想L9', brand: 'li', type: '增程式', price: 459800, image: '/cars/li-l9.jpg' },
          { id: '4', name: '小鹏G9', brand: 'xiaopeng', type: '纯电动', price: 309900, image: '/cars/xpeng-g9.jpg' },
          { id: '5', name: '蔚来ES8', brand: 'nio', type: '纯电动', price: 496000, image: '/cars/nio-es8.jpg' },
          { id: '6', name: '问界M7', brand: 'seres', type: '增程式', price: 249800, image: '/cars/seres-m7.jpg' },
          { id: '7', name: '极氪001', brand: 'zeekr', type: '纯电动', price: 300000, image: '/cars/zeekr-001.jpg' },
          { id: '8', name: '深蓝SL03', brand: 'deepal', type: '纯电动', price: 169900, image: '/cars/deepal-sl03.jpg' },
        ];
        setCars(mockCars);
      } catch (error) {
        console.error('加载品牌数据失败:', error);
      } finally {
        setIsLoading(false);
      }
    };

    loadBrandData();
  }, [user, router]);

  // 获取所有字母
  const alphabets = ['全部', ...Array.from(new Set(brands.map(b => b.alphabet)))].sort();
  
  // 获取所有国家
  const countries = ['全部', ...Array.from(new Set(brands.map(b => b.country)))].sort();

  // 过滤品牌
  const filteredBrands = brands.filter(brand => {
    const matchesSearch = brand.name.toLowerCase().includes(searchTerm.toLowerCase()) || 
                         brand.brand.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesAlphabet = selectedAlphabet === '全部' || brand.alphabet === selectedAlphabet;
    const matchesCountry = selectedCountry === '全部' || brand.country === selectedCountry;
    
    return matchesSearch && matchesAlphabet && matchesCountry;
  });

  // 获取热门品牌
  const hotBrands = brands.filter(brand => brand.hot === '1');

  // 获取品牌相关车辆
  const getBrandCars = (brandKey: string) => {
    return cars.filter(car => car.brand === brandKey).slice(0, 3);
  };

  if (!user || user.role !== 'admin') {
    return null;
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="animate-spin rounded-full h-16 w-16 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  return (
    <>
      {/* Header */}
      <div className="mb-8">
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">品牌管理</h1>
            <p className="text-gray-600">探索和管理汽车品牌信息</p>
          </div>
          <div className="flex items-center space-x-4">
            <div className="text-sm text-gray-500">
              共 {brands.length} 个品牌
            </div>
          </div>
        </div>
      </div>

      {/* Search and Filters */}
      <div className="bg-white rounded-lg shadow-sm p-6 mb-8">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          {/* Search */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">搜索品牌</label>
            <input
              type="text"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              placeholder="输入品牌名称或拼音..."
              className="w-full border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          {/* Alphabet Filter */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">按字母筛选</label>
            <select
              value={selectedAlphabet}
              onChange={(e) => setSelectedAlphabet(e.target.value)}
              className="w-full border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              {alphabets.map(alpha => (
                <option key={alpha} value={alpha}>{alpha}</option>
              ))}
            </select>
          </div>

          {/* Country Filter */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">按国家筛选</label>
            <select
              value={selectedCountry}
              onChange={(e) => setSelectedCountry(e.target.value)}
              className="w-full border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              {countries.map(country => (
                <option key={country} value={country}>{country}</option>
              ))}
            </select>
          </div>
        </div>
      </div>

      {/* Hot Brands */}
      {hotBrands.length > 0 && (
        <div className="mb-8">
          <h2 className="text-xl font-semibold text-gray-900 mb-4">热门品牌</h2>
          <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
            {hotBrands.map(brand => (
              <Link
                key={brand.brand}
                href={`/admin/brands/${brand.brand}`}
                className="bg-white rounded-lg shadow-sm p-4 text-center hover:shadow-md transition-shadow cursor-pointer group"
              >
                <div className="w-16 h-16 mx-auto mb-3 bg-gradient-to-br from-yellow-400 to-orange-500 rounded-full flex items-center justify-center text-white text-2xl font-bold">
                  {brand.alphabet}
                </div>
                <h3 className="font-semibold text-gray-900 group-hover:text-blue-600 transition-colors">
                  {brand.name}
                </h3>
                <p className="text-sm text-gray-500">{brand.country}</p>
                <span className="inline-block mt-2 px-2 py-1 bg-red-100 text-red-600 text-xs rounded-full">
                  热门
                </span>
              </Link>
            ))}
          </div>
        </div>
      )}

      {/* All Brands Grid */}
      <div className="bg-white rounded-lg shadow-sm overflow-hidden mb-8">
        <div className="px-6 py-4 border-b border-gray-200 bg-gray-50">
          <div className="flex justify-between items-center">
            <h2 className="text-xl font-semibold text-gray-900">所有品牌</h2>
            <span className="text-sm text-gray-500">
              显示 {filteredBrands.length} 个品牌
            </span>
          </div>
        </div>
        
        <div className="p-6">
          {filteredBrands.length === 0 ? (
            <div className="text-center py-12">
              <div className="text-gray-400 text-6xl mb-4">🚗</div>
              <h3 className="text-lg font-medium text-gray-900 mb-2">未找到匹配的品牌</h3>
              <p className="text-gray-500">尝试调整搜索条件或筛选器</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
              {filteredBrands.map((brand) => {
                const brandCars = getBrandCars(brand.brand);
                
                return (
                  <Link
                    key={brand.brand}
                    href={`/admin/brands/${brand.brand}`}
                    className="border border-gray-200 rounded-lg p-6 hover:shadow-lg transition-all duration-300 cursor-pointer group bg-white"
                  >
                    {/* Brand Header */}
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex items-center">
                        <div className="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white text-lg font-bold mr-3">
                          {brand.alphabet}
                        </div>
                        <div>
                          <h3 className="text-lg font-semibold text-gray-900 group-hover:text-blue-600 transition-colors">
                            {brand.name}
                          </h3>
                          <p className="text-sm text-gray-500">{brand.country}</p>
                        </div>
                      </div>
                      {brand.hot === '1' && (
                        <span className="px-2 py-1 bg-red-100 text-red-600 text-xs font-semibold rounded-full">
                          热门
                        </span>
                      )}
                    </div>

                    {/* Brand Description */}
                    <p className="text-gray-600 text-sm mb-4 line-clamp-2 leading-relaxed">
                      {brand.desc}
                    </p>

                    {/* Recommended Cars */}
                    {brandCars.length > 0 && (
                      <div className="mb-4">
                        <h4 className="text-sm font-medium text-gray-700 mb-2">推荐车型</h4>
                        <div className="space-y-2">
                          {brandCars.map(car => (
                            <div key={car.id} className="flex items-center justify-between text-sm">
                              <span className="text-gray-600">{car.name}</span>
                              <span className="font-semibold text-blue-600">
                                {car.price.toLocaleString()}元
                              </span>
                            </div>
                          ))}
                        </div>
                      </div>
                    )}

                    {/* Action Button */}
                    <div className="flex justify-between items-center pt-4 border-t border-gray-100">
                      <span className="text-xs text-gray-500">
                        {brandCars.length} 款车型
                      </span>
                      <button className="text-blue-600 text-sm font-medium hover:text-blue-700 transition-colors">
                        查看详情 →
                      </button>
                    </div>
                  </Link>
                );
              })}
            </div>
          )}
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <div className="bg-white rounded-lg shadow-sm p-6 border border-blue-100">
          <div className="text-2xl font-bold text-blue-600">{brands.length}</div>
          <div className="text-gray-600">总品牌数</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm p-6 border border-green-100">
          <div className="text-2xl font-bold text-green-600">
            {hotBrands.length}
          </div>
          <div className="text-gray-600">热门品牌</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm p-6 border border-purple-100">
          <div className="text-2xl font-bold text-purple-600">
            {Array.from(new Set(brands.map(b => b.country))).length}
          </div>
          <div className="text-gray-600">涉及国家</div>
        </div>
        <div className="bg-white rounded-lg shadow-sm p-6 border border-orange-100">
          <div className="text-2xl font-bold text-orange-600">
            {cars.length}
          </div>
          <div className="text-gray-600">推荐车型</div>
        </div>
      </div>
    </>
  );
}